//
//  WPForumViewController.m
//  ZhongChouPingTai
//
//  Created by WeiPan on 16/3/30.
//  Copyright © 2016年 HuaYiSoftware. All rights reserved.
//

#import "WPForumViewController.h"
#import "WPForumModel.h"
#import "WPForumTableViewCell.h"
#import "WPTopicDetailViewController.h"

static NSString *const kUITableViewCellIdentifier = @"cellIdentifier";

static CGFloat timerInterval = 3.0f;

@interface WPForumViewController ()<UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>{
    NSMutableArray *_iamgeViews;/**< 存储图片视图 */
    NSMutableArray *_imageNames;/**< 存储图片名字 */
    NSMutableArray * _urlImageNames;/**< 网络图片名字 */
    NSMutableArray * _urlArray;/**< 活动网址 */
}
@property (nonatomic, strong) UIView * headView;/**< 表头 */
@property (nonatomic, strong) UITextField * searchTextField;/**< 搜索框 */
@property (nonatomic, strong) UIScrollView * imageScrollView;/**< 轮播视图 */
@property (nonatomic, strong) UIPageControl * pageControl;/**< 分页显示器 */
@property (nonatomic, strong) NSTimer * timer;/**< 计时器 */
@property (nonatomic, strong) UITableView * forumTableView;/**< 论坛列表 */
@property (nonatomic, strong) NSMutableArray * forumDataSource;/**< 论坛数据源 */
@property (nonatomic, strong) NSArray * nextVCHtmls;/**< 详情界面html资源 */
- (void)initializeDataSource; /**< 初始化数据源 */
- (void)initializeUserInterface; /**< 初始化用户界面 */
- (void)refreshData;/**< 刷新数据 */
- (void)insertImageViewInScroll;/**< 在滚动视图中插入3个图片视图 */
- (void)insertImageInImageView;/**< 在图片视图上显示图片 */


@end

@implementation WPForumViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeDataSource];
    [self initializeUserInterface];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.timer.fireDate = [NSDate distantPast];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    //暂停timer
    [self.timer setFireDate:[NSDate distantFuture]];
    
}
#pragma mark - init
- (void)initializeDataSource {
    _imageNames = [NSMutableArray arrayWithArray:@[@"banner1.png", @"banner2.png", @"banner3.png", @"banner4.png"]];
    self.nextVCHtmls = @[@"topic1.html", @"topic.html", @"topic2.html"];
    self.forumDataSource = [NSMutableArray arrayWithCapacity:0];
    WPForumModel * model = [WPForumModel new];
    model.title = @"BIGBANG VIP 2016三巡";
    model.firstImage = @"banner1.png";
    model.secondImage = @"banner1.png";
    model.thirdImage = @"banner1.png";
    model.time = @"13:14";
    model.attentionCount = @"872";
    model.supportCount = @"2764";
    [_forumDataSource addObject:model];
}
- (void)initializeUserInterface {
    self.title = @"论坛";
    [self.view addSubview:self.forumTableView];
}
#pragma mark - responds events
- (void)respondsToTimer {
    [self.imageScrollView setContentOffset:CGPointMake(2*CGRectGetWidth(self.view.bounds), 0) animated:YES];
}
- (void)respondsToImageViewTap {
    WPTopicDetailViewController * vc = [WPTopicDetailViewController new];
    vc.htmeName = _nextVCHtmls[0];
    [self pushToNextController:vc withVCTitle:@"话题详情"];
}
#pragma mark - 刷新数据
- (void)refreshData {
    
}
#pragma mark - 协议UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _forumDataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WPForumTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kUITableViewCellIdentifier];
    if (!cell) {
        cell = [[WPForumTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kUITableViewCellIdentifier];
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell refreshDataWithModel:_forumDataSource[indexPath.row]];
    return cell;
}
#pragma mark - UITableViewDelegate
//设置每一行高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 148*DHFlexibleHorizontalMutiplier();
}
//用户点击了某一行
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WPTopicDetailViewController * vc = [WPTopicDetailViewController new];
    vc.htmeName = _nextVCHtmls[indexPath.row+1];
    [self pushToNextController:vc withVCTitle:@"话题详情"];
}
#pragma mark - 滚动视图协议
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == _forumTableView) {
        return;
    }
    //往右滑
    if (scrollView.contentOffset.x >= 2*CGRectGetWidth(self.view.bounds)) {
        if (_urlImageNames.count) {
            NSString *firstObject = [_urlImageNames.firstObject mutableCopy];
            [_urlImageNames removeObjectAtIndex:0];
            [_urlImageNames addObject:firstObject];
            self.pageControl.currentPage = self.pageControl.currentPage == _urlImageNames.count - 1? 0:self.pageControl.currentPage+1;
        } else {
            NSString *firstObject = [_imageNames.firstObject mutableCopy];
            [_imageNames removeObjectAtIndex:0];
            [_imageNames addObject:firstObject];
            self.pageControl.currentPage = self.pageControl.currentPage == _imageNames.count - 1? 0:self.pageControl.currentPage+1;
        }
    }
    //往左滑
    else if (scrollView.contentOffset.x <= 0) {
        if (_urlImageNames.count) {
            NSString *lastObject = [_urlImageNames.lastObject mutableCopy];
            [_urlImageNames removeObject:lastObject];
            [_urlImageNames insertObject:lastObject atIndex:0];
            self.pageControl.currentPage = self.pageControl.currentPage == 0? _urlImageNames.count - 1:self.pageControl.currentPage-1;
        } else {
            NSString *lastObject = [_imageNames.lastObject mutableCopy];
            [_imageNames removeObject:lastObject];
            [_imageNames insertObject:lastObject atIndex:0];
            self.pageControl.currentPage = self.pageControl.currentPage == 0? _imageNames.count - 1:self.pageControl.currentPage-1;
        }
        
    }else {
        //停在中间
        return;
    }
    [self insertImageInImageView];
    //更新偏移量
    scrollView.contentOffset = CGPointMake(CGRectGetWidth(scrollView.bounds), 0);
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    //暂停timer
    if (scrollView == _forumTableView) {
        return;
    }
    _timer.fireDate = [NSDate distantFuture];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    //从结束拖动开始计算延迟2s再启动
    if (scrollView == _forumTableView) {
        return;
    }
    _timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:timerInterval];
}
#pragma mark - private methods
- (void)insertImageViewInScroll {
    _iamgeViews = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < 3; i++) {
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(i*SCREEN_SIZE.width, 0, SCREEN_SIZE.width, CGRectGetHeight(self.imageScrollView.bounds))];
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer * tapges = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(respondsToImageViewTap)];
        [imageView addGestureRecognizer:tapges];
        [_imageScrollView addSubview:imageView];
        //将图片视图植入——imageViews 便于便利数组
        [_iamgeViews addObject:imageView];
    }
}
- (void)insertImageInImageView {
    NSInteger index = 0;
    for (UIImageView *imageView in _iamgeViews) {
        if (_urlImageNames.count) {
            index = index == _urlImageNames.count ? _urlImageNames.count - 1:index;
            NSURL * imageUrl = [NSURL URLWithString:_urlImageNames[index]];
            UIImage * placeImge = imageView.image;
            [imageView sd_setImageWithURL:imageUrl placeholderImage:placeImge];
        } else {
            imageView.image = IMAGE_NAME(_imageNames[index]);
        }
        index++;
    }
}
#pragma mark - getter
- (UIView *)headView {
    if (!_headView) {
        _headView = ({
            UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, navBar_Fheight+5*DHFlexibleHorizontalMutiplier(), SCREEN_SIZE.width, 195*DHFlexibleHorizontalMutiplier())];
            [view addSubview:self.imageScrollView];
            [view addSubview:self.pageControl];
            [self insertImageViewInScroll];
            [self insertImageInImageView];
            view.backgroundColor = BGCOLOR;
            UILabel * lab = [[UILabel alloc]initWithFrame:CGRectMake(10*DHFlexibleHorizontalMutiplier(), CGRectGetMaxY(self.imageScrollView.frame), 300, 20*DHFlexibleHorizontalMutiplier())];
            lab.backgroundColor = [UIColor clearColor];
            lab.font = [UIFont systemFontOfSize:10*DHFlexibleHorizontalMutiplier()];
            lab.textColor = COLOR_RGB(151, 151, 151, 1);
            lab.text = @"今日热门";
            [view addSubview:lab];
            view;
        });
    }
    return _headView;
}
- (UIScrollView *)imageScrollView {
    if (!_imageScrollView) {
        _imageScrollView = ({
            UIScrollView * view = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_SIZE.width, 175*DHFlexibleHorizontalMutiplier())];
            view.showsHorizontalScrollIndicator = NO;
            view.showsVerticalScrollIndicator = NO;
            view.pagingEnabled = YES;
            view.bounces = NO;
            view.delegate = self;
            view.contentSize = CGSizeMake(CGRectGetWidth(self.view.frame)*3, 0);
            view.contentOffset = CGPointMake(CGRectGetWidth(view.bounds), 0);
            view;
        });
    }
    return _imageScrollView;
}
- (UIPageControl *)pageControl {
    if (!_pageControl) {
        _pageControl = ({
            UIPageControl * control = [[UIPageControl alloc]initWithFrame:CGRectMake(250*DHFlexibleHorizontalMutiplier(), CGRectGetMaxY(self.imageScrollView.frame) - 30*DHFlexibleHorizontalMutiplier(), 50*DHFlexibleHorizontalMutiplier(), 30*DHFlexibleHorizontalMutiplier())];
            control.numberOfPages = _imageNames.count;
            control.currentPage = 0;
            control.hidesForSinglePage = YES;
            control.pageIndicatorTintColor = COLOR_RGB(230, 231, 232, 1);
            control.currentPageIndicatorTintColor = COLOR_RGB(140, 141, 145, 1);
            control;
        });
    }
    return _pageControl;
}

- (NSTimer *)timer {
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:timerInterval target:self selector:@selector(respondsToTimer) userInfo:nil repeats:YES];
    }
    return _timer;
}
- (UITableView *)forumTableView {
    if (!_forumTableView) {
        _forumTableView = ({
            UITableView * tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, navBar_Fheight, SCREEN_SIZE.width, SCREEN_SIZE.height - navBar_Fheight-CGRectGetHeight(self.tabBarController.tabBar.bounds)) style:UITableViewStylePlain];
            tableview.dataSource = self;
            tableview.delegate = self;
            tableview.tableHeaderView = self.headView;
            tableview.tableFooterView = [UIView new];
            tableview.pagingEnabled = NO;
            tableview.bounces = NO;
            tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
            tableview;
        });
    }
    return _forumTableView;
}
@end
